<template>
  <div class="manage">
    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handelClose">
      <!--新增表单信息 -->
      <el-form ref="form" :rules="rules" :inline="true" :model="form" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-input placeholder="请输入姓名" v-model="form.username"></el-input>
        </el-form-item>
        <br/>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            style="border:1px dashed #d1d1d1"
            class="avatar-uploader"
            :action="uploadURL"
            name="uploadFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <br/>
        <el-form-item label="昵称" prop="nickname">
          <el-input placeholder="请输入昵称" v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-show="passwordShow">
          <el-input placeholder="请输入密码" v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input placeholder="请输入电话" v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input placeholder="请输入身份证号" v-model="form.idNumber"></el-input>
        </el-form-item>
        <el-form-item label="角色" v-show="show" prop="">
          <el-select v-model="form.roleIdsInt" multiple placeholder="请选择">
            <el-option
              v-for="item in roles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              :disabled="item.delFlag==0? false : true">
            </el-option>
          </el-select>
        </el-form-item>
        <br/>
        <el-form-item label="部门" prop="">
          <el-tree :data="deptList" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <div class="manage-header">
      <el-button @click="handelAdd" type="primary">
        <i class="el-icon-plus"></i>新增
      </el-button>
      <!--form 搜索区-->
      <el-form :inline="true" :model="form">
        <el-form-item>
          <el-input placeholder="请输入姓名" v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入电话" v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="common-table">
      <el-row :gutter="20">
        <el-col :span="4">
          <div style="width: 100%;height: 450px;">
            <el-tree :data="deptList" :props="defaultProps" default-expand-all @node-click="handleNodeClickuserForm"></el-tree>
          </div>
        </el-col>
        <el-col :span="20">
          <div style="height: 450px;">
            <!--内容-->
            <el-table
              height="90%"
              :data="tableData"
              style="width: 100%"
              stripe>
              <el-table-column type="index" label="序号" fixed></el-table-column>
              <el-table-column prop="username" label="姓名" fixed></el-table-column>
              <el-table-column prop="" label="头像" fixed>
                <template slot-scope="scope">
                  <el-avatar shape="square" v-if="scope.row.avatar" :src="scope.row.avatar">
                    <img shape="square" src="../assets/fallback.png"/>
                  </el-avatar>
                </template>
              </el-table-column>
              <el-table-column prop="nickname" label="昵称" width="100" fixed></el-table-column>
              <el-table-column prop="deptName" label="部门"></el-table-column>
              <el-table-column prop="roleName" label="角色" width="150"></el-table-column>
              <el-table-column prop="email" label="邮箱" width="190"></el-table-column>
              <el-table-column prop="phone" label="电话" width="130"></el-table-column>
              <el-table-column prop="idNumber" label="身份证号" width="200"></el-table-column>
              <el-table-column
                prop="createTime"
                width="170"
                label="创建时间">
              </el-table-column>
              <el-table-column prop="" label="状态">
                <template slot-scope="scope">
                  <a @click="updateDelFlag(scope.row)">
                    <el-switch
                      v-model="scope.row.delFlag==0 ? true : false"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </el-switch>
                  </a>
                </template>
              </el-table-column>
              <el-table-column prop="" label="操作" width="165" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="handelEditAdmin(scope.row)"><i class="el-icon-edit"></i>修改</el-button>
                  <el-button type="text" size="mini" @click="handelDelAdmin(scope.row)"><i class="el-icon-delete"></i>删除</el-button>
                  <el-tooltip placement="bottom" effect="light">
                    <div slot="content">
                      <el-button size="mini" type="text" @click="handelAdminPassword(scope.row)">重置密码</el-button>
                    </div>
                    <el-button type="text" size="mini"><i class="el-icon-d-arrow-right"></i>更多</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      <!--页码-->
      <div class="pager">
        <el-pagination
          layout="prev, pager, next"
          :total="this.total"
          @current-change="handelPage">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
    import { listAdmin, saveOrUpdateAdmin, delAdmin, listRole, listDeptTree, editRoleByIdAdmin } from "../api"
    export default {
        name: "Admin",
        data(){
            return{
                dialogVisible:false,
                form: {
                    id: '',
                    username: '',
                    avatar: '',
                    nickname: '',
                    password: '',
                    email: '',
                    phone: '',
                    idNumber: '',
                    delFlag: '',
                    deptId:'',
                    roleIdsInt:[]
                },
                rules:{
                    username: [
                        {required: true,message: '请输入姓名'}
                    ],
                    nickname: [
                        {required: true,message: '请输入昵称'}
                    ],
                    password: [
                        {required: true,message: '请输入密码'}
                    ],
                    email: [
                        {required: true,message: '请输入邮箱'}
                    ],
                    phone: [
                        {required: true,message: '请输入电话'}
                    ],
                    idNumber: [
                        {required: true,message: '请输入身份证号码'}
                    ]
                },
                tableData: [],
                modelType: 0,  //0：新增，1：修改
                total: 0,
                pageData:{
                    page: 1,
                    limit: 10
                },
                //查询条件
                userForm: {
                    username: "",
                    phone: "",
                    deptId: ""
                },
                roles: [],
                deptList: [],
                defaultProps: {
                    children: 'depts',
                    label: 'deptName'
                },
                show: false,
                passwordShow:true,
                uploadURL: 'http://localhost:8080/admin/uploadAvatar'
            }
        },
        methods:{
            //文件上传成功
            handleAvatarSuccess(res, file) {
                this.form.avatar=file.response
                //this.imageUrl = URL.createObjectURL(file.raw);
            },
            //文件上传之前
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';
                const isLt3M = file.size / 1024 / 1024 < 3;
                if (!isJPG && !isPNG) {
                    this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
                    return false;
                }
                if (!isLt3M) {
                    this.$message.error('上传头像图片大小不能超过 3MB!');
                    return false;
                }
                return true;
            },
            handleNodeClick(data) {
                //部门id
                this.form.deptId=data.deptId;
            },
            handleNodeClickuserForm(data){
                this.userForm.deptId=data.deptId;
                this.pageData.page=1
                this.listAdmin();
            },
            //提交用户表单
            submit(){
                //进行校验
                this.$refs.form.validate((valid)=>{
                    if (valid){
                        if (this.modelType == 0){
                            //新增
                            this.form.id=null;
                            saveOrUpdateAdmin(this.form).then(({ data })=>{
                                this.$message({
                                    type: data.type,
                                    message: data.message
                                });
                                this.listAdmin();
                            });
                        }else{
                            //修改
                            saveOrUpdateAdmin(this.form).then(({ data }) => {
                                this.$message({
                                    type: data.type,
                                    message: data.message
                                });
                                this.listAdmin();
                            });
                        }
                        this.handelClose();
                    }
                });
            },
            //弹窗关闭的时候
            handelClose(){
                //重置表单
                this.$refs.form.resetFields();
                this.dialogVisible=false;
            },
            //点击取消
            cancel(){
                this.handelClose();
            },
            //编辑
            handelEditAdmin(row){
                //角色出现
                this.show=true;
                //密码隐藏
                this.passwordShow=false;
                this.modelType=1;
                this.dialogVisible=true;
                this.editRoleByIdAdmin(row);
            },
            //获取管理员的角色
            editRoleByIdAdmin(row){
                //需要对当前的数据进行深拷贝，否则会出错，不能直接this.form=row;
                this.form=JSON.parse(JSON.stringify(row));
                editRoleByIdAdmin(this.form).then(({data})=>{
                    if (data!=null){
                        data.forEach(item=>{
                            if (this.form.roleIdsInt==null){
                                this.form.roleIdsInt=[];
                            }
                            this.form.roleIdsInt.push(item.roleId);
                        });
                    }
                });
            },
            //修改状态
            updateDelFlag(row){
                this.$confirm('确定要“'+(row.delFlag ===0 ? "停用" : "启用")+'”“'+row.username+'”用户吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    row.delFlag=(row.delFlag === 0 ? 1 : 0);
                    saveOrUpdateAdmin(row).then(({ data }) => {
                        this.listAdmin();
                    });
                    this.$message({
                        type: "success",
                        message: "修改成功"
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            //删除
            handelDelAdmin(row){
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delAdmin(row).then(({ data })=>{
                        this.listAdmin();
                        this.$message({
                            type: data.type,
                            message: data.message
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //新增
            handelAdd(){
                this.show=false;
                this.passwordShow=true;
                this.form={
                    id: '',
                    username: '',
                    avatar: '',
                    nickname: '',
                    password: '',
                    email: '',
                    phone: '',
                    idNumber: '',
                    delFlag: '',
                    deptId:'',
                    roleIdsInt:[]
                };
                this.modelType=0;
                this.dialogVisible=true;
            },
            //获取列表
            listAdmin(){
                listAdmin({...this.userForm,...this.pageData}).then(( {data} )=>{
                    //console.log(data,"获取的")
                    this.tableData=data.list;
                    //如果data.count不存在 就为0
                    this.total=data.count || 0;
                });
            },
            //获取角色列表
            listRole(){
                listRole().then(({ data })=>{
                    this.roles=data;
                    /*data.forEach(item=>{
                        this.roles.push({
                            roleId:item.roleId,
                            roleName:item.roleName,
                            disabled: item.delFlag==0 ? false : true
                        });
                    });*/
                });
            },
            //获取部门列表
            listDeptTree(){
                listDeptTree().then(({data})=>{
                    data.forEach(item=>{
                        this.deptList.push(item);
                    })
                });
            },
            //获取页码
            handelPage(val){
                //console.log(val);
                this.pageData.page=val;
                this.listAdmin();
            },
            //条件查询
            onSubmit(){
                this.listAdmin();
            },
            //重置密码
            handelAdminPassword(row){
                this.editRoleByIdAdmin(row);
                const  username=this.form.username;
                this.$prompt('请输入“'+username+'”的新密码', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValidator: (item)=>{
                        item=item.replace(/\s*/g,"");
                        if (item==" " || item==""){
                            return false;
                        }else{
                            return true
                        }
                    },
                    inputErrorMessage: '密码不能为空'
                }).then(({ value }) => {
                    if (value==null){
                        this.$message.error('密码不能为空');
                        return ;
                    }
                    value=value.replace(/\s*/g,"");
                    this.form.password=value;
                    saveOrUpdateAdmin(this.form).then(({ data }) => {
                        this.$message({
                            type: data.type,
                            message: data.message
                        });
                        this.listAdmin();
                    });
                    this.$message({
                        type: 'success',
                        message: username+'的新的密码是: ' + value
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消输入'
                    });
                });
            }
        },
        //页面首次加载时调用的地方
        mounted() {
            this.listAdmin();
            this.listRole();
            this.listDeptTree();
        }
    }
</script>

<style lang="less" scoped>
.manage{
  height: 90%;
  .manage-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .common-table{
    position: relative;
    //动态计算高度
    height: calc(100% - 62px);
    .pager{
      position: absolute;
      bottom: 0;
      right: 20px;
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
